class MobileCategory
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Taggable

  belongs_to :userinfo
  # validate :must_set_one_conditions
  field :title
  field :num, type: Integer, default:0
  field :conditions, type: Array, default:[] #[{"name":"brand","ord":0,"limit":10}]

  #validates :title, presence: true, uniqueness: true

  attr_readonly *fields.keys

  def product_count

    Product.shop_id(self['userinfo_id']).where(mobile_category_id:self.id,:state_id => State.online.id).size
  end

  def products
    Product.shop_id(self['userinfo_id']).where(mobile_category_id:self.id)
  end


  def self.get_cache_list_by_userinfo_id(userinfo_id)

    redis = Redis.new
    list_json = redis.get("mobile_category_#{userinfo_id}")

    list_data = list_json.present? ? JSON.parse(list_json) : []
    if !list_data.present?
      list_data = MobileCategory.where({:userinfo_id => userinfo_id}).reject { |category| category.product_count==0 }
      redis.set("mobile_category_#{userinfo_id}",list_data.to_json)
      redis.expire("mobile_category_#{userinfo_id}",60*20)
    else
      list_data.collect!{|u| MobileCategory.new(u)}
    end
    list_data
  end

end
